<template>
	<view class="points-container">
		<!-- 顶部导航栏 -->

		<!-- 积分展示 -->
		<view class="points-display">
			<text class="points-number">{{totalPoints}}</text>
			<text class="points-text">我的积分</text>
			<view class="points-detail-btn" @click="goToPointsDetail">
				<text>积分明细</text>
				<uni-icons type="right" size="14" color="#FFFFFF"></uni-icons>
			</view>
		</view>

		<!-- 签到日历 -->
		<view class="sign-in-section">
			<view class="section-header">
				<text class="section-title">每日签到</text>
				<!-- <text class="sign-in-desc">连续签到7天可额外获得50积分</text> -->
			</view>

			<view class="calendar">
				<!-- 星期标题 -->
				<view class="week-header">
					<text v-for="day in weekDays" :key="day" class="week-day">{{day}}</text>
				</view>

				<!-- 日期网格 -->
				<view class="day-grid">
					<view
						v-for="(day, index) in calendarDays"
						:key="index"
						class="day-item"
						:class="{
							'empty': !day.date,
							'signed': day.signed,
							'today': day.isToday,
							'disabled': day.disabled
						}"
						@click="signIn(day)"
					>
						<text class="day-number">{{day.date || ''}}</text>
						<view v-if="day.signed" class="signed-mark"></view>
					</view>
				</view>
			</view>

			<view class="sign-in-btn-wrapper">
				<button class="sign-in-btn" :disabled="todaySigned" @click="signInToday">
					{{todaySigned ? '今日已签到' : '立即签到'}}
				</button>
			</view>

			<!-- <view class="sign-in-progress">
				<view class="progress-bar">
					<view class="progress-inner" :style="{width: (continuousDays/7*100) + '%'}"></view>
				</view>
				<view class="progress-days">已连续签到 {{continuousDays}} 天</view>
			</view> -->
		</view>

		<!-- 任务列表 -->
		<view class="task-section">
			<view class="section-title">每日任务</view>
			<view class="task-list">
				<view class="task-item" v-for="(task, index) in dailyTasks" :key="'daily'+index">
					<view class="task-icon">
						<uni-icons :type="task.icon" size="24" color="#007AFF"></uni-icons>
					</view>
					<view class="task-info">
						<view class="task-name">{{task.name}}</view>
						<view class="task-points">
							<uni-icons type="star" size="14" color="#FFB800"></uni-icons>
							<text>{{task.points}}积分</text>
							<image v-if="task.showProgress" :src="task.progressIcon" class="progress-icon"></image>
						</view>
					</view>
					<view class="task-status">
						<button
							class="task-button"
							:class="{'completed': task.completed}"
							@click="completeTask(task)"
						>
							{{task.completed ? '已完成' : '去完成'}}
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- <view class="task-section">
			<view class="section-title">基础任务</view>
			<view class="task-list">
				<view class="task-item" v-for="(task, index) in basicTasks" :key="'basic'+index">
					<view class="task-icon">
						<uni-icons :type="task.icon" size="24" color="#007AFF"></uni-icons>
					</view>
					<view class="task-info">
						<view class="task-name">{{task.name}}</view>
						<view class="task-points">
							<uni-icons type="star" size="14" color="#FFB800"></uni-icons>
							<text>{{task.points}}积分</text>
						</view>
					</view>
					<view class="task-status">
						<button
							class="task-button"
							:class="{'completed': task.completed}"
							@click="completeTask(task)"
						>
							{{task.completed ? '已完成' : '去完成'}}
						</button>
					</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>


export default {
	data() {
		return {
			totalPoints: 62, // 初始化为0，后续从接口获取
			weekDays: ['日', '一', '二', '三', '四', '五', '六'],
			calendarDays: [],
			signedDays: [], // 已签到的日期，格式 ['2023-07-19', '2023-07-20']
			todaySigned: false,
			continuousDays: 0,
			dailyTasks: [
				{
					name: '每日登录',
					points: 20,
					icon: 'person-filled',
					completed: false,
					type: 'login'
				},
				{
					name: '阅读文章 (0/3)',
					points: 30,
					icon: 'book',
					completed: false,
					type: 'read',
					showProgress: true,
					progressIcon: '../../static/img/read.png'
				}
			]
		}
	},
	created() {
		this.getUserPoints();
		this.generateCalendar();
		this.loadSignData();
		this.checkLoginTask();
	},
	methods: {
		// 获取用户积分
		getUserPoints() {
			uni.showLoading({
				title: '加载中...'
			});

			// 移除org_id参数，让后端通过用户信息获取
			this.$boya.NGet("/app/points/user_points", {}, (res) => {
				if (res.code === 200) {
					// 修正数据结构，后端返回的是 res.data，不是 res.data.total_points
					this.totalPoints = res.data.points || 0; // 当前积分
					console.log('获取积分成功:', res.data);
				} else {
					uni.showToast({
						title: res.msg || '获取积分失败',
						icon: 'none'
					});
				}
				uni.hideLoading();
			}, (err) => {
				console.error('获取积分失败', err);
				uni.showToast({
					title: err.msg,
					icon: 'none'
				});
				uni.hideLoading();
			});
		},

		// 更新积分（完成任务或签到后调用）
		updateUserPoints(addPoints, type) {
			// 本地先更新积分，提高用户体验
			this.totalPoints += addPoints;

			// 注意：这里不需要调用积分更新接口，因为具体的积分操作（如签到、阅读等）
			// 应该调用对应的积分获取接口，而不是通用的积分更新接口
			// 积分的发放应该通过具体的业务接口来完成

			console.log(`积分更新：+${addPoints}，类型：${type}，当前积分：${this.totalPoints}`);
		},

		navigateBack() {
			uni.navigateBack()
		},
		completeTask(task) {
			if (!task.completed) {
				// 任务完成处理逻辑
				if (task.type === 'read') {
					// 跳转到阅读文章页面
					uni.navigateTo({
						url: '/pages/news/news'
					});
					return;
				}

				this.completeTaskAndAddPoints(task);
			}
		},
		completeTaskAndAddPoints(task) {
			// 更新任务状态
			task.completed = true;

			// 更新积分并记录
			this.updateUserPoints(task.points, task.type);

			// 保存完成状态到本地存储
			const completedTasks = uni.getStorageSync('completedTasks') || {};
			const today = new Date();
			const todayString = this.formatDate(today.getFullYear(), today.getMonth(), today.getDate());

			if (!completedTasks[todayString]) {
				completedTasks[todayString] = [];
			}

			if (!completedTasks[todayString].includes(task.type)) {
				completedTasks[todayString].push(task.type);
			}

			uni.setStorageSync('completedTasks', completedTasks);

			// 显示提示
			uni.showToast({
				title: `完成任务，+${task.points}积分`,
				icon: 'success'
			});
		},
		// 检查登录任务
		checkLoginTask() {
			// 获取今日已完成的任务
			const completedTasks = uni.getStorageSync('completedTasks') || {};
			const today = new Date();
			const todayString = this.formatDate(today.getFullYear(), today.getMonth(), today.getDate());

			const todayCompletedTasks = completedTasks[todayString] || [];

			// 更新任务状态
			this.dailyTasks.forEach(task => {
				if (todayCompletedTasks.includes(task.type)) {
					task.completed = true;
				}
			});

			// 如果今天还没有登录任务记录，则自动完成登录任务
			const loginTask = this.dailyTasks.find(task => task.type === 'login');
			if (loginTask && !loginTask.completed) {
				this.completeTaskAndAddPoints(loginTask);
			}
		},
		goToPointsDetail() {
			// 跳转到积分明细页面
			uni.navigateTo({
				url: "/pages/points/pointsDetail",
				fail(err) {
					console.log('跳转失败', err);
				}
			})
		},
		// 生成日历数据
		generateCalendar() {
			const today = new Date();
			const year = today.getFullYear();
			const month = today.getMonth();

			// 获取当月第一天
			const firstDay = new Date(year, month, 1);
			// 获取当月最后一天
			const lastDay = new Date(year, month + 1, 0);

			// 当月总天数
			const daysInMonth = lastDay.getDate();

			// 第一天是周几（0是周日，1是周一...）
			const firstDayOfWeek = firstDay.getDay();

			// 填充日历数组
			this.calendarDays = [];

			// 添加上个月的占位空白
			for (let i = 0; i < firstDayOfWeek; i++) {
				this.calendarDays.push({
					date: null,
					signed: false,
					isToday: false,
					disabled: true
				});
			}

			// 添加当月的日期
			const todayDate = today.getDate();
			for (let i = 1; i <= daysInMonth; i++) {
				this.calendarDays.push({
					date: i,
					signed: false,
					isToday: i === todayDate,
					disabled: i > todayDate,
					dateString: this.formatDate(year, month, i)
				});
			}

			// 如果不足42个，添加下个月的占位空白
			const remainingCells = 42 - this.calendarDays.length;
			for (let i = 0; i < remainingCells; i++) {
				this.calendarDays.push({
					date: null,
					signed: false,
					isToday: false,
					disabled: true
				});
			}
		},
		// 格式化日期为 YYYY-MM-DD
		formatDate(year, month, day) {
			const formattedMonth = (month + 1).toString().padStart(2, '0');
			const formattedDay = day.toString().padStart(2, '0');
			return `${year}-${formattedMonth}-${formattedDay}`;
		},
		// 加载签到数据
		loadSignData() {
			// 从服务器获取签到数据
			uni.showLoading({
				title: '加载中...'
			});

			// 移除org_id参数，让后端通过用户信息获取
			this.$boya.NGet("/app/points/sign_logs", {}, (res) => {
				if (res.code === 200) {
					// 处理签到记录数据
					const signLogs = res.data || [];
					this.signedDays = signLogs.map(log => log.sign_date);

					// 检查今天是否已签到
					const today = new Date();
					const todayString = this.formatDate(today.getFullYear(), today.getMonth(), today.getDate());
					this.todaySigned = this.signedDays.includes(todayString);

					// 更新日历上的签到状态
					this.updateCalendarWithSignData();

					// 计算连续签到天数
					this.calculateContinuousDays();

					console.log('签到数据加载成功:', signLogs);
				} else {
					console.error('获取签到数据失败:', res.msg);
					// 如果接口失败，使用本地数据作为备用方案
					this.useLocalSignData();
				}
				uni.hideLoading();
			}, (err) => {
				console.error('获取签到数据失败', err);
				// 网络错误时使用本地数据
				this.useLocalSignData();
				uni.hideLoading();
			});
		},
		// 使用本地签到数据（作为备用方案）
		useLocalSignData() {
			const signedData = uni.getStorageSync('signedDays') || [];
			this.signedDays = signedData;

			// 更新日历上的签到状态
			this.updateCalendarWithSignData();

			// 检查今天是否已签到
			const today = new Date();
			const todayString = this.formatDate(today.getFullYear(), today.getMonth(), today.getDate());
			this.todaySigned = this.signedDays.includes(todayString);

			// 计算连续签到天数
			this.calculateContinuousDays();

			console.log('使用本地签到数据:', this.signedDays);
		},
		// 更新日历上的签到状态
		updateCalendarWithSignData() {
			this.calendarDays.forEach(day => {
				if (day.dateString && this.signedDays.includes(day.dateString)) {
					day.signed = true;
				}
			});
		},
		// 计算连续签到天数
		calculateContinuousDays() {
			if (this.signedDays.length === 0) {
				this.continuousDays = 0;
				return;
			}

			const today = new Date();
			let continuousDays = 0;
			let currentDate = new Date(today);

			// 如果今天签到了，从今天开始计算
			// 如果今天没签到，从昨天开始计算
			if (!this.todaySigned) {
				currentDate.setDate(currentDate.getDate() - 1);
			}

			while (true) {
				const dateString = this.formatDate(
					currentDate.getFullYear(),
					currentDate.getMonth(),
					currentDate.getDate()
				);

				if (this.signedDays.includes(dateString)) {
					continuousDays++;
					currentDate.setDate(currentDate.getDate() - 1);
				} else {
					break;
				}
			}

			this.continuousDays = continuousDays;
		},
		// 签到
		signInToday() {
			if (this.todaySigned) return;

			uni.showLoading({
				title: '签到中...'
			});

			// 移除org_id参数，让后端通过用户信息获取
			this.$boya.NGet("/app/points/sign_in", {}, (res) => {
				if (res.code === 200) {
					const today = new Date();
					const todayString = this.formatDate(today.getFullYear(), today.getMonth(), today.getDate());

					// 添加到签到记录
					if (!this.signedDays.includes(todayString)) {
						this.signedDays.push(todayString);
					}

					// 保存到本地存储（作为备份）
					uni.setStorageSync('signedDays', this.signedDays);

					// 更新签到状态并保存到本地存储
					this.todaySigned = true;
					uni.setStorageSync('todaySigned', true);
					uni.setStorageSync('lastSignDate', todayString);

					// 更新日历上的签到状态
					this.calendarDays.forEach(day => {
						if (day.dateString === todayString) {
							day.signed = true;
						}
					});

					// 更新连续签到天数
					this.continuousDays = res.data.continuous_days || (this.continuousDays + 1);

					// 获取签到积分奖励信息
					const signInPoints = res.data.points || 10;
					const extraPoints = res.data.bonus_points || 0;

					// 显示签到成功提示
					if (extraPoints > 0) {
						uni.showToast({
							title: `连续签到${this.continuousDays}天，奖励${extraPoints}积分！`,
							icon: 'none',
							duration: 2000
						});
					} else {
						uni.showToast({
							title: `签到成功，+${signInPoints}积分`,
							icon: 'success'
						});
					}

					// 刷新用户总积分
					this.getUserPoints();

				} else {
					uni.showToast({
						title: res.msg || '签到失败，请稍后再试',
						icon: 'none'
					});
				}
				uni.hideLoading();
			}, (err) => {
				console.error('签到失败', err);
				uni.showToast({
					title: err.msg,
					icon: 'none'
				});
				uni.hideLoading();
			});
		},
		// 点击日历上的日期
		signIn(day) {
			if (day.disabled || !day.date || day.signed) return;

			// 只允许签今天的
			if (day.isToday) {
				this.signInToday();
			}
		}
	}
}
</script>

<style lang="scss">
.points-container {
	min-height: 100vh;
	background-color: #007AFF;
	padding-bottom: 40rpx;

	.nav-bar {
		height: 88rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		padding-top: var(--status-bar-height);

		.back {
			padding: 20rpx;
		}

		.title {
			color: #FFFFFF;
			font-size: 36rpx;
			font-weight: 500;
			flex: 1;
			text-align: center;
		}
	}

	.points-display {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx 0;

		.points-number {
			font-size: 80rpx;
			color: #FFFFFF;
			font-weight: bold;
		}

		.points-text {
			font-size: 28rpx;
			color: #FFFFFF;
			margin-top: 20rpx;
		}

		.points-detail-btn {
			background-color: #FFB800;
			color: #FFFFFF;
			font-size: 24rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			border: none;
			margin-top: 20rpx;
			display: flex;
			align-items: center;

			text {
				margin-right: 8rpx;
			}
		}
	}

	.sign-in-section {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin: 30rpx;
		padding: 30rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
			}

			.sign-in-desc {
				font-size: 24rpx;
				color: #999999;
			}
		}

		.calendar {
			margin-bottom: 30rpx;

			.week-header {
				display: flex;
				justify-content: space-around;
				margin-bottom: 20rpx;

				.week-day {
					width: 70rpx;
					text-align: center;
					font-size: 28rpx;
					color: #999999;
				}
			}

			.day-grid {
				display: flex;
				flex-wrap: wrap;

				.day-item {
					width: 14.28%;
					height: 70rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					position: relative;
					margin-bottom: 20rpx;

					.day-number {
						font-size: 28rpx;
						color: #333333;
					}

					.signed-mark {
						position: absolute;
						bottom: 0;
						width: 8rpx;
						height: 8rpx;
						border-radius: 50%;
						background-color: #007AFF;
					}

					&.empty {
						pointer-events: none;
					}

					&.signed {
						.day-number {
							color: #007AFF;
							font-weight: bold;
						}
					}

					&.today {
						.day-number {
							width: 60rpx;
							height: 60rpx;
							border-radius: 30rpx;
							background-color: #FFB800;
							color: #FFFFFF;
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}

					&.disabled {
						opacity: 0.5;
						pointer-events: none;
					}
				}
			}
		}

		.sign-in-btn-wrapper {
			display: flex;
			justify-content: center;
			margin-bottom: 30rpx;

			.sign-in-btn {
				background-color: #007AFF;
				color: #FFFFFF;
				font-size: 30rpx;
				padding: 20rpx 0;
				width: 80%;
				border-radius: 40rpx;
				border: none;

				&[disabled] {
					background-color: #CCCCCC;
				}
			}
		}

		.sign-in-progress {
			.progress-bar {
				height: 16rpx;
				background-color: #F5F5F5;
				border-radius: 8rpx;
				overflow: hidden;
				margin-bottom: 10rpx;

				.progress-inner {
					height: 100%;
					background-color: #007AFF;
					border-radius: 8rpx;
				}
			}

			.progress-days {
				font-size: 24rpx;
				color: #999999;
				text-align: center;
			}
		}
	}

	.task-section {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin: 30rpx;
		padding: 30rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 30rpx;
		}

		.task-list {
			.task-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1px solid #F5F5F5;

				&:last-child {
					border-bottom: none;
				}

				.task-icon {
					width: 80rpx;
					height: 80rpx;
					background-color: #F0F7FF;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.task-info {
					flex: 1;
					margin-left: 20rpx;

					.task-name {
						font-size: 28rpx;
						color: #333333;
					}

					.task-points {
						display: flex;
						align-items: center;
						margin-top: 10rpx;

						text {
							font-size: 24rpx;
							color: #999999;
							margin-left: 8rpx;
						}

						.progress-icon {
							width: 30rpx;
							height: 30rpx;
							margin-left: 10rpx;
						}
					}
				}

				.task-status {
					.task-button {
						background-color: #FFB800;
						color: #FFFFFF;
						font-size: 24rpx;
						padding: 10rpx 30rpx;
						border-radius: 30rpx;
						border: none;

						&.completed {
							background-color: #CCCCCC;
						}
					}
				}
			}
		}
	}
}
</style>